import MSFile

class MSObject:
    def __init__(self, path, objId):
        self.storage = MSFile.File(path, str(objId))

        self.objId  = objId
        self.events = []

    def setMSID(self, msId):
        self.storage.meta['msId'] = msId

    def setPCNID(self, pcnId):
        self.storage.meta['pcnId'] = pcnId

    def setSKEY(self, skey):
        self.storage.meta['skey'] = skey

    def setOfflineCritical(self, enableOfflineCritical=False, offlineCriticalTimeout=600):
        self.storage.meta['enableOfflineCritical'] = enableOfflineCritical
        self.storage.meta['offlineCriticalTimeout'] = offlineCriticalTimeout

    def open(self):
        self.events = self.storage.load()
        if self.storage.txn == 0:
            self.storage.meta = {}
            self.storage.reset()

    def flush(self): self.storage.save(self.events)
        

##########################
if __name__ == "__main__":
    import sys
    if len(sys.argv) != 2: print "Usage: %s <storage_root>" % (sys.argv[0])
    g_root = sys.argv[1]
    
    def case1():
        f1 = MSFile.File(g_root, 'test_obj')
        f1.destroy()

        o1 = MSObject(g_root, 'test_obj')
        o1.open()
        if o1.storage.txn != 0: raise RuntimeError('case1: failed 1')
        if o1.storage.meta != {}: raise RuntimeError('case1: failed 2')

        o1.storage.meta['test_param'] = 79
        o1.flush()

    def case2():
        o = MSObject(g_root, 'test_obj')
        o.open()
        if o.storage.txn != 1: raise RuntimeError('case2: failed 1')
        if o.storage.meta['test_param'] != 79: raise RuntimeError('case2: failed 2')

    case1()
    case2()
